// pages/user-time-records/user-time-records.js
const app = getApp()

Page({
  data: {
    timeRecords: [],
    loading: true,
    refreshing: false,
    currentPage: 1,
    hasMore: true,
    dateRange: {
      start: '',
      end: ''
    }
  },

  onLoad() {
    this.loadTimeRecords()
  },

  onShow() {
    this.loadTimeRecords()
  },

  onPullDownRefresh() {
    this.setData({
      refreshing: true,
      currentPage: 1,
      hasMore: true
    })
    this.loadTimeRecords().then(() => {
      wx.stopPullDownRefresh()
      this.setData({
        refreshing: false
      })
    })
  },

  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadMoreTimeRecords()
    }
  },

  // 加载时间记录列表
  loadTimeRecords() {
    this.setData({
      loading: true
    })

    return app.userRequest({
      url: '/getTimeRecords',
      data: {
        page: 1,
        start_date: this.data.dateRange.start,
        end_date: this.data.dateRange.end
      }
    }).then((res) => {
      const timeRecords = res.data || []
      this.setData({
        timeRecords: timeRecords,
        loading: false,
        hasMore: timeRecords.length >= 20
      })
    }).catch((err) => {
      console.error('获取时间记录失败:', err)
      this.setData({
        loading: false
      })
      wx.showToast({
        title: '获取时间记录失败',
        icon: 'none'
      })
    })
  },

  // 加载更多时间记录
  loadMoreTimeRecords() {
    if (this.data.loading || !this.data.hasMore) return

    this.setData({
      loading: true
    })

    const nextPage = this.data.currentPage + 1

    app.userRequest({
      url: '/getTimeRecords',
      data: {
        page: nextPage,
        start_date: this.data.dateRange.start,
        end_date: this.data.dateRange.end
      }
    }).then((res) => {
      const newTimeRecords = res.data || []
      const allTimeRecords = [...this.data.timeRecords, ...newTimeRecords]
      
      this.setData({
        timeRecords: allTimeRecords,
        currentPage: nextPage,
        hasMore: newTimeRecords.length >= 20,
        loading: false
      })
    }).catch((err) => {
      console.error('加载更多时间记录失败:', err)
      this.setData({
        loading: false
      })
      wx.showToast({
        title: '加载更多失败',
        icon: 'none'
      })
    })
  },

  // 选择开始日期
  onStartDateChange(e) {
    this.setData({
      'dateRange.start': e.detail.value
    })
  },

  // 选择结束日期
  onEndDateChange(e) {
    this.setData({
      'dateRange.end': e.detail.value
    })
  },

  // 搜索时间记录
  searchTimeRecords() {
    this.setData({
      currentPage: 1,
      hasMore: true
    })
    this.loadTimeRecords()
  },

  // 重置搜索
  resetSearch() {
    this.setData({
      dateRange: {
        start: '',
        end: ''
      },
      currentPage: 1,
      hasMore: true
    })
    this.loadTimeRecords()
  }
})
